package com.chang.service;

import com.chang.tools.Tools;
import com.chang.pojo.User;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class UserService {
    private String filename ;
    File file;
    public HashMap<String, User> Cashdb;
    Scanner scanner;
    Tools tools;

    public UserService() throws IOException {
        tools =new Tools();
        filename= tools.File_Path+"\\src\\com\\chang\\db\\userinfo.txt";
        file = new File(filename);
        scanner = new Scanner(System.in);
        readUser();
    }

    void readUser() throws IOException {
        Cashdb = new HashMap<>();
        FileReader reader = new FileReader(file);// 低级流
        BufferedReader br = new BufferedReader(reader);//高级流
        String str;
        while ((str = br.readLine()) != null) {
            String[] user_arr = str.split("&");
            User user = new User();
            user.setName(user_arr[0]);
            user.setId(user_arr[1]);
            user.setKeywords(user_arr[2]);
            user.setState((user_arr[3].equals("0"))?false:true);
            Cashdb.put(user.getId(), user);
        }
    }

    public void writeUser() throws IOException {
        String all_txt = "";
        Set<String> keyset = Cashdb.keySet();
        Iterator<String> iterator = keyset.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            User value = Cashdb.get(key);
            all_txt += value.toString() + "\n";
            FileWriter writer = new FileWriter(file);
            writer.write(all_txt);
            writer.flush();
        }
    }

    public void addUser() throws IOException, InterruptedException {
        User user = new User();
        System.out.println("正在为您创建账户，请稍后...");
        Thread.sleep(1000);
        System.out.print("请输入您要创建的用户名称:");
        String iname = scanner.next();
        String sid;
        user.setName(iname);
        boolean ti = false;
        do {
            sid = "6023" + (int) (1000 + (Math.random() * 9000));
            if (Cashdb.get(sid) != null) {
                ti = true;
            } else {
                ti = false;
            }
        } while (ti);
        user.setId(sid);
        System.out.println("已为您生成一个专属卡号：" + user.getId());
        boolean o;
        do {
            System.out.print("请输入您的密码:");
            String ipwd = scanner.next();
            System.out.print("请您再次输入密码:");
            String jpwd = scanner.next();
            if (ipwd.equalsIgnoreCase(jpwd)) {
                user.setKeywords(ipwd);
                o = false;
            } else {
                System.out.println("密码前后不一致，请您重新输入");
                o = true;
            }
        } while (o);
        System.out.println("注册成功！");
        System.out.println("您的账号信息：" + "id:" + user.getId() + ",name:" + user.getName() + ",账号" + (user.getState() ? "正常" : "异常"));
        System.out.println("----------------");
        Cashdb.put(user.getId(), user);
        writeUser();
        String t;
        do {
            System.out.println("是否用户登录(否为退出系统)(Y|N)");
            t = scanner.next();
            if (t.equalsIgnoreCase("n")) {
                System.exit(0);
            } else if (!t.equalsIgnoreCase("y")) {
                System.out.println("输入错误，请您重新输入!");
            }
        } while (!(t.equalsIgnoreCase("y") || t.equalsIgnoreCase("n")));
    }

    public boolean logonUser(User user1) throws InterruptedException {

        if (!user1.getState()) {
            System.out.println("你的账号异常,请联系管理员!");
            System.out.println("自动为您退出账号...");
            Thread.sleep(1000);
            return false;
        }
        boolean iscontinue = true;
        int count = 5;
        do {
            System.out.print("请输入您的密码：");
            String pwd = scanner.next();
            if (pwd.equals(user1.getKeywords())) {
                iscontinue = false;
            } else {
                //可以添加还有几次机会
                count--;
                if (count == 0) {
                    System.out.println("您的密码次数已经用完，即将退出系统");
                    Thread.sleep(1000);
                    return false;
                }
                System.out.println("您的密码输入有误,还剩下" + count + "次机会，请重试!");
                iscontinue = true;
            }
        } while (iscontinue);

        return true;
    }
    public void logoff(String id) throws InterruptedException, IOException {
        boolean iscontinue = true;
        User user = Cashdb.get(id);
        String kwd;
        int count = 5;
        do {
            System.out.print("请输入您的密码:");
            kwd = scanner.next();
            if (kwd.equals(user.getKeywords())) {
                iscontinue = false;
            } else {
                //可以添加还有几次机会
                count--;
                if (count == 0) {
                    System.out.println("您的密码次数已经用完，即将退出系统");
                    Thread.sleep(1000);
                    System.exit(0);
                }
                System.out.println("您的密码输入有误,还剩下" + count + "次机会，请重试!");
                iscontinue = true;
            }
        } while (iscontinue);
        System.out.println("确定注销账号?(Y|N)");
        String oi = scanner.next();
        if (oi.equalsIgnoreCase("y")) {
            Cashdb.remove(id);
            writeUser();
            System.exit(0);
        } else if (!oi.equalsIgnoreCase("n")) {
            System.out.println("输入错误");
        }
    }

    public void showAllUser() {
        Set<String> keyset = Cashdb.keySet();
        Iterator<String> iterator = keyset.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = Cashdb.get(key).getName();
            System.out.println("姓名:" + value + ",id:" + key+",账号"+(Cashdb.get(key).getState()?"正常":"异常"));
        }
    }
}
